package cn.wolfcode.luowowo.website.web.advice;

import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 统一异常类
 *
 * @ControllerAdvice  控制层功能增强注解
 *
 *  给请求映射方法进行功能增强: 在进入映射方法前或者执行完映射后进行功能增强
 *
 *  此处功能: 执行映射方法后出现异常后怎么处理
 */
@ControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(LogicException.class)
    public void logicExp(Exception e, HttpServletResponse resp, Model model, HttpServletRequest req) throws IOException {
        e.printStackTrace();
        resp.setContentType("text/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSONString(new AjaxResult(false, e.getMessage())));
    }

    @ExceptionHandler(RuntimeException.class)
    public void runTimeExp(Exception e, HttpServletResponse resp) throws IOException {
        e.printStackTrace();
        resp.setContentType("text/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSONString(new AjaxResult(false, "系统出现未知异常，请联系客服。")));
    }
}